package com.example.netty.tcp.codec;

import com.example.netty.tcp.message.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonDecoder extends MessageToMessageDecoder<ByteBuf> {
    private static final Logger logger = LoggerFactory.getLogger(JsonDecoder.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        logger.debug("进入 JsonDecoder.decode 方法");
        // 直接读取所有可读字节为JSON字符串
        String json = in.toString(StandardCharsets.UTF_8);
        logger.debug("收到JSON消息: {}", json);

        // 解析消息类型
        BaseMessage message = parseMessage(json);
        if (message != null) {
            out.add(message);
        }
    }

    // 保持原有解析逻辑不变
    private BaseMessage parseMessage(String json) throws Exception {
        int msgType = extractMsgType(json);
        Class<? extends BaseMessage> messageClass = getMessageClass(msgType);
        if (messageClass != null) {
            return mapper.readValue(json, messageClass);
        }
        logger.warn("未知消息类型: {}", msgType);
        return null;
    }

    // 保持原有消息类型提取逻辑
    private int extractMsgType(String json) {
        int startIndex = json.indexOf("\"msgType\":");
        if (startIndex == -1) return -1;
        startIndex += "\"msgType\":".length();
        int endIndex = json.indexOf(',', startIndex);
        if (endIndex == -1) endIndex = json.indexOf('}', startIndex);
        if (endIndex == -1) return -1;
        try {
            return Integer.parseInt(json.substring(startIndex, endIndex).trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    // 保持消息类型映射不变
    private Class<? extends BaseMessage> getMessageClass(int msgType) {
        switch (msgType) {
            case 110: return LoginRequest.class;
            case 111: return LoginResponse.class;
            case 310: return AttributeReport.class;
            case 311: return AttributeReportResponse.class;
            case 410: return AlarmReport.class;
            case 411: return AlarmReportResponse.class;
            case 500: return ControlRequest.class;
            case 501: return ControlResponse.class;
            case 210: return ConfigurationQueryRequest.class;
            case 211: return ConfigurationQueryResponse.class;
            default: return null;
        }
    }
}
